package com.wy.component.image;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.commons.io.FileUtils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.wy.component.file.FileUtil;

public class ImageUtil {

	public static void imageCompression(String path) {
		String url = path.substring(0,path.lastIndexOf("\\") + 1);
		String name = path.substring(path.lastIndexOf("\\") + 1);
		File f = new File(path);
		float per = (300 * 1024) / f.length();
		if (f.length() > 300 * 1024) {
			per = (float) (300 * 1024) / f.length();
			per = (float) (per + (1 - per) / 5);
		} else {
			per = (float) 1.0;
		}
		Tosmallerpic(url, new File(path), "_small", name, (float) per);
		//替换原图,移除临时文件
		String newPathExt = path.substring(path.lastIndexOf(".") + 1);
		String newPathName = path.substring(0,path.lastIndexOf("."));
		String newPath = newPathName + "_small." + newPathExt;
		try {
			FileUtil.copyFile(new File(newPath), new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileUtils.deleteQuietly(new File(newPath));
	}

	/**
	 * 改变图片的大小到宽为size，然后高随着宽等比例变化
	 * @param file 上传的图片的输入流
	 * @param f 改变了图片的大小后，把图片的流输出到目标OutputStream
	 * @param size 新图片的宽
	 * @param format 新图片的格式
	 * @throws IOException
	 */
	public static void imageResize(String sourcePath, String destPath, int size, String format) throws IOException {
		File sourceFile = new File(sourcePath);
		FileInputStream is = new FileInputStream(sourcePath);
		File destFile = new File(destPath);
		destFile.createNewFile();
		FileOutputStream out = new FileOutputStream(destFile);
		BufferedImage prevImage = ImageIO.read(sourceFile);
		double width = prevImage.getWidth();
		double height = prevImage.getHeight();
		double percent = size/width;
		int newWidth = (int)(width * percent);
		int newHeight = (int)(height * percent);
		BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);
		Graphics graphics = image.createGraphics();
		graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null);
		ImageIO.write(image, format, out);
		out.flush();
		is.close();
		out.close();
		FileUtils.deleteQuietly(sourceFile);
	}

	public static void imageCut(String sourceSrc,int x, int y,int width,int height, String format, String destSrc) {
		try {
			String tempPath = destSrc.substring(0, destSrc.lastIndexOf("/"));
			String ext = destSrc.substring(destSrc.lastIndexOf(".") + 1);
			String tempDest = tempPath + "/" + UUID.randomUUID().toString() + "." + ext;
			// 取得图片读入器
			Iterator readers = ImageIO.getImageReadersByFormatName(format);
			ImageReader reader = (ImageReader) readers.next();
			// 取得图片读入流
			InputStream source = new FileInputStream(sourceSrc);
			ImageInputStream iis = ImageIO.createImageInputStream(source);
			reader.setInput(iis, true);
			// 图片参数
			ImageReadParam param = reader.getDefaultReadParam();
			// 100，200是左上起始位置，300就是取宽度为300的，就是从100开始取300宽，就是横向100~400，同理纵向200~350的区域就取高度150
			// Rectangle rect = new Rectangle(100, 200, 300, 150);//
			Rectangle rect = new Rectangle(x, y, width, height);
			param.setSourceRegion(rect);
			BufferedImage bi = reader.read(0, param);
			ImageIO.write(bi, format, new File(tempDest));
			FileUtils.deleteQuietly(new File(sourceSrc));
			
	        BufferedImage sourceImg1;
			sourceImg1 = ImageIO.read(new FileInputStream(tempDest));
			//宽 >= 高
			if(sourceImg1.getWidth() >= sourceImg1.getHeight()){
				if(sourceImg1.getHeight() < 300){
					ImageUtil.imageResize(tempDest, destSrc, new Double(305d / sourceImg1.getHeight() * sourceImg1.getWidth()).intValue(), ext);
				}else{
					FileUtil.copyFile(new File(tempDest), new File(destSrc));
					FileUtils.deleteQuietly(new File(tempDest));
				}
			}
			//宽 < 高
			else{
				if(sourceImg1.getWidth() < 300){
					ImageUtil.imageResize(tempDest, destSrc, 305, ext);
				}else{
					FileUtil.copyFile(new File(tempDest), new File(destSrc));
					FileUtils.deleteQuietly(new File(tempDest));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void imageResize(String sourcePath, String destPath, int width,int height, String format) throws IOException {
		File sourceFile = new File(sourcePath);
		FileInputStream is = new FileInputStream(sourcePath);
		File destFile = new File(destPath);
		destFile.createNewFile();
		FileOutputStream out = new FileOutputStream(destFile);
		BufferedImage prevImage = ImageIO.read(sourceFile);
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics graphics = image.createGraphics();
		graphics.drawImage(prevImage, 0, 0, width, height, null);
		ImageIO.write(image, format, out);
		out.flush();
		is.close();
		out.close();
		FileUtils.deleteQuietly(sourceFile);
	}

	/**
	 * 
	 * @param f
	 *            图片所在的文件夹路径
	 * @param filelist
	 *            图片路径
	 * @param ext
	 *            扩展名
	 * @param n
	 *            图片名
	 * @param w
	 *            目标宽
	 * @param h
	 *            目标高
	 * @param per
	 *            百分比
	 */
	private static void Tosmallerpic(String f, File filelist, String ext,
			String n, float per) {
		Image src;
		try {
			src = javax.imageio.ImageIO.read(filelist); // 构造Image对象

			String img_midname = f + n.substring(0, n.indexOf(".")) + ext
					+ n.substring(n.indexOf("."));
			int old_w = src.getWidth(null); // 得到源图宽
			int old_h = src.getHeight(null);
			int w = old_w;
			int h = old_h;
			int new_w = 0;
			int new_h = 0; // 得到源图长

			double w2 = (old_w * 1.00) / (w * 1.00);
			double h2 = (old_h * 1.00) / (h * 1.00);

			// 图片跟据长宽留白，成一个正方形图。
			BufferedImage oldpic;
			/*
			 * if(old_w>old_h) { oldpic=new
			 * BufferedImage(old_w,old_w,BufferedImage.TYPE_INT_RGB); }else{
			 * if(old_w<old_h){ oldpic=new
			 * BufferedImage(old_h,old_h,BufferedImage.TYPE_INT_RGB); }else{
			 * oldpic=new BufferedImage(old_w,old_h,BufferedImage.TYPE_INT_RGB);
			 * } }
			 */
			oldpic = new BufferedImage(old_w, old_h, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = oldpic.createGraphics();
			g.setColor(Color.white);

			if (old_w > old_h) {
				g.fillRect(0, 0, old_w, old_w);
				g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
				// g.fillRect(0, 0, old_w, old_w);
				// g.drawImage(src, 0, (old_w - old_h) / 2, old_w, old_h,
				// Color.white, null);
			} else {
				if (old_w < old_h) {
					g.fillRect(0, 0, old_h, old_h);
					g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
					// g.fillRect(0,0,old_h,old_h);
					// g.drawImage(src, (old_h - old_w) / 2, 0, old_w, old_h,
					// Color.white, null);
				} else {
					// g.fillRect(0,0,old_h,old_h);
					g.drawImage(src.getScaledInstance(old_w, old_h,
							Image.SCALE_SMOOTH), 0, 0, null);
				}
			}

			g.fillRect(0, 0, old_w, old_h);
			g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
			g.dispose();
			src = oldpic;
			// 图片调整为方形结束
			if (old_w > w)
				new_w = (int) Math.round(old_w / w2);
			else
				new_w = old_w;
			if (old_h > h)
				new_h = (int) Math.round(old_h / h2);// 计算新图长宽
			else
				new_h = old_h;
			new_h = h;
			new_w = w;

			BufferedImage tag = new BufferedImage(new_w, new_h,
					BufferedImage.TYPE_INT_RGB);
			// tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
			tag.getGraphics().drawImage(
					src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,
					0, null);
			FileOutputStream newimage = new FileOutputStream(img_midname); // 输出到文件流
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
			JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
			/* 压缩质量 */
			jep.setQuality(per, true);
			encoder.encode(tag, jep);
			// encoder.encode(tag); //近JPEG编码
			newimage.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
}
